package com.yang.net.tcp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author yds
 * @program net-sokect_stduy
 * @description 作为tcp协议 聊天室的服务器
 * @create 2020-09-27 16:02
 **/
public class TcpServer {
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket accept=null;
        InputStream in=null;
        ByteArrayOutputStream bos=null;
        try {
            //1.提供一种服务器地址
            serverSocket = new ServerSocket(9999);
            while(true) {
                //2. 等待客户端连接
                accept = serverSocket.accept();
                //3. 读取客户端消息
                in = accept.getInputStream();
            /*传统写法,但是过来消息太长,byte太小容易中断数据,产生乱码
            byte[] buffer = new byte[1024];
            int len;
            while((len=in.read(buffer))!=-1){
                String s = new String(buffer, 0, len);
                System.out.println(s);
            }
            */
                //使用管道流
                bos = new ByteArrayOutputStream();
                int len;
                byte[] buffer = new byte[1024];
                while ((len = in.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                System.out.println(bos.toString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(bos!=null){
                    bos.close();
                }
                if(in!=null){
                    in.close();
                }
                if(accept!=null){
                    accept.close();
                }
                if(serverSocket!=null){
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
           ;
        }
    }

}